<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from "vue";
import payWechatIcon from "~/assets/pay-wechat.png";
import payAlipayIcon from "~/assets/pay-ali.png";
import payCardIcon from "~/assets/pay-card.png";
import { useUserStore } from "~/store/useUser";
import { getWechatPayCode, getAlipayPayCode, createOrderBank, createOrder} from "~/api/order";
import { useRoute } from "vue-router";
import { useOrderStore } from "~/store/useOrder";
import { useRouter } from "vue-router";
import {
  buyerOrderDetail,
  getRiseOrderWechatCode,
  getRiseOrderAlipayCode,
  getCompanyPayInfo,
} from "~/api/order";
import { ElMessageBox } from "element-plus";
import { ElMessage } from "element-plus";
import {Check} from "@element-plus/icons-vue";
import DialogPayQRCode from "~/components/dialog/PayQRCode.vue";

useSeoMeta({
  title: "支付 - 技能猴子",
  ogTitle: "支付 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

const userStore = useUserStore();
const orderStore = useOrderStore();
const userInfo = ref({});
const buyerInfo = ref({});
const payQRCodeVisible = ref(false);
const addCompanyVisible = ref(false);
const orderId = ref("");
const type = ref("");
const goodsId = ref("");
const route = useRoute();
const router = useRouter();
const orderExpireTimeText = ref("");
const timer = ref();
const orderDetails = ref<any>({});
const amount = ref(0);

onMounted(() => {
  // 确保正确获取用户信息
  userInfo.value = { ...userStore.getUserInfo };
  buyerInfo.value = userInfo.value.buyerInfo || null;
  
  // 安全地设置企业支付信息（只有在企业支付选项存在时）
  if (payWayList.value[2]) {
    payWayList.value[2].company = (userInfo.value as any).companyName || (buyerInfo.value as any)?.companyName || "";
  }

  console.log('Pay page mounted - userInfo:', userInfo.value);

  orderId.value = route.query.orderSn as string;
  goodsId.value = route.query.gid as string;
  type.value = route.query.type as string;

  if (orderId.value) {
    getOrderDetails();
  }

  timer.value = setInterval(() => {
    orderExpireTimeText.value = expireTime();
  }, 1000);
  // companyPayInfo();
});

// 添加对用户信息变化的监听
watch(() => userStore.getUserInfo, (newVal) => {
  userInfo.value = { ...newVal };
  buyerInfo.value = userInfo.value.buyerInfo || null;
  
  // 安全地设置企业支付信息（只有在企业支付选项存在时）
  if (payWayList.value[2]) {
    payWayList.value[2].company = (userInfo.value as any).companyName || (buyerInfo.value as any)?.companyName || "";
  }
  
  console.log('Pay page updated userInfo:', userInfo.value);
}, { deep: true });

// 监听登录状态变化
watch(() => userStore.isLogin, (newVal) => {
  console.log('Pay page login status changed:', newVal);
}, { immediate: true });

watch(type, (newVal) => {
  console.log("type", newVal);
  if (newVal === "j") {
    getOrderDetails();
  }
});

const getOrderDetails = async () => {
  try {
    const { data } = await buyerOrderDetail({
      orderSn: orderId.value,
    });
    orderDetails.value = data;
    orderStore.setPayInfo(data); // 更新 store
    if (type.value === "j") {
      const riseRecord = orderDetails.value.riseRecord;
      if (riseRecord && riseRecord.id) {
        amount.value = riseRecord.amount;
      }
    }
  } catch (e) {
    console.log(e);
  }
};

const payWay = ref("wechat");
const payWayList = ref([
  {
    name: "微信支付",
    value: "wechat",
    icon: payWechatIcon,
    checked: true,
    description: "即时到账",
    company: "",
  },
  {
    name: "支付宝",
    value: "alipay",
    icon: payAlipayIcon,
    checked: false,
    description: "大额专享",
    company: "",
  },
  {
    name: "企业钱包",
    value: "WALLET",
    icon: payCardIcon,
    checked: false,
    description: "企业专用钱包",
    company: "",
  },
]);

function selectPayWay(selectedValue: string) {
  // 使用 companyId 或企业名称判断是否已入驻企业，兼容旧的 addCompany 标识
  const hasCompany = Boolean((userInfo.value as any).companyId || (userInfo.value as any).addCompany === 1 || (buyerInfo.value as any)?.companyName);

  if (selectedValue === "card" && !hasCompany) {
    ElMessageBox.confirm("请先完善企业入驻信息后再使用企业支付", "提示", {
      confirmButtonText: "去完善",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      router.push("/enterpriseJoin");
    });
    return;
  }
  payWay.value = selectedValue;
  payWayList.value.forEach((item) => {
    item.checked = item.value === selectedValue;
  });
  if (selectedValue === 'card' && hasCompany) {
    companyPayInfo();
  }
}

const joinCompany = () => {
  addCompanyVisible.value = false;
  addPhoneVisible.value = true;
};

// 更新payData结构以匹配PayQRCode组件的期望格式
const updatePayDataForQRCode = (result) => {
  const { data } = result;
  
  // 根据URL内容判断支付类型
  const url = data.payUrl || data.qrCode;
  let actualPayType = 'alipay'; // 默认支付宝
  
  // 如果当前选择的是企业钱包，则使用WALLET类型
  if (payWay.value === 'WALLET') {
    actualPayType = 'wallet';
  } else if (url && url.includes('weixin://')) {
    actualPayType = 'weixin';
  } else if (url && url.includes('alipay')) {
    actualPayType = 'alipay';
  } else if (data.paymentType === 'WECHAT') {
    actualPayType = 'weixin';
  } else if (data.paymentType === 'ALIPAY') {
    actualPayType = 'alipay';
  }
  
  console.log('支付数据分析:', {
    originalPaymentType: data.paymentType,
    url: url,
    detectedPayType: actualPayType,
    payWayValue: payWay.value
  });
  
  payData.value = {
    payUrl: data.payUrl,
    qrCode: data.qrCode,
    outTradeNo: data.outTradeNo,
    paymentType: payWay.value, // 使用当前选择的支付方式
    payType: actualPayType,
    url: url,
    expireTime: Date.now() + 15 * 60 * 1000
  };
};

// 点击去支付，生成支付二维码
const payData = ref("");
const qrcodeLoading = ref(false);
const payHandle = async () => {
  if(payWay.value === "card"){
    ElMessageBox.prompt('请填写打款流水号', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(({ value }) => {
      serialNumber.value = value
      createQYOrder()
    })
    return
  }
  qrcodeLoading.value = true;
  try {
    // 订单加价支付
    if (type.value === "j" && amount.value) {
      if (payWay.value === "wechat") {
        // 微信
        const res = await getRiseOrderWechatCode({
          orderSn: orderId.value,
        });
        payData.value = {
          ...res.data,
          payType: "weixin",
          expireTime: Date.now() + 15 * 60 * 1000,
        };
        payQRCodeVisible.value = true;
        return;
      } else if (payWay.value === "alipay") {
        // 支付宝
        const res = await getRiseOrderAlipayCode({
          orderSn: orderId.value,
        });
        payData.value = {
          ...res.data,
          payType: "alipay",
          expireTime: Date.now() + 15 * 60 * 1000,
        };
        payQRCodeVisible.value = true;
        return;
      } else if (payWay.value === "WALLET") {
        // 企业钱包
        const paymentData = {
          orderSn: orderId.value,
          paymentScene: "WEB",
          paymentType: "WALLET",
          returnUrl: window.location.origin + "/orderDetails?orderSn=" + orderId.value
        };
        const paymentResult = await createOrder(paymentData);
        if (paymentResult.code === 200 && paymentResult.data) {
          updatePayDataForQRCode(paymentResult);
          payQRCodeVisible.value = true;
        } else {
          ElMessage.error(paymentResult.msg || "创建企业钱包支付订单失败");
        }
        return;
      }
    }

    // 使用新的支付接口处理商品订单支付
    const paymentData = {
      orderSn: orderId.value,
      paymentScene: "WEB",
      paymentType: payWay.value === "wechat" ? "WECHAT" : 
                  payWay.value === "alipay" ? "ALIPAY" : 
                  payWay.value === "WALLET" ? "WALLET" : "ALIPAY",
      returnUrl: window.location.origin + "/orderDetails?orderSn=" + orderId.value
    };

    console.log('调用支付接口，参数:', paymentData);
    const paymentResult = await createOrder(paymentData);
    console.log('支付接口返回结果:', paymentResult);

    if (paymentResult.code === 200 && paymentResult.data) {
      // 更新payData以匹配PayQRCode组件的期望格式
      updatePayDataForQRCode(paymentResult);
      payQRCodeVisible.value = true;
    } else {
      ElMessage.error(paymentResult.msg || "创建支付订单失败");
    }
  } catch (e) {
    console.error('支付处理失败:', e);
    ElMessage.error("生成支付订单失败");
  } finally {
    qrcodeLoading.value = false;
  }
};
// 用订单创建时间计算订单过期时间,订单有效期为2小时,计算出过期日期时间，格式：yyyy-MM-dd HH:mm:ss
const expireTime = () => {
  if (orderStore.payInfo.payClose === 1) return "已过期";
  const orderCreateTime = new Date(orderStore.payInfo.createTime).getTime();
  const expireTime = orderCreateTime + 2 * 60 * 60 * 1000;
  const expireDate = new Date(expireTime);
  const now = new Date();
  const diff = expireDate.getTime() - now.getTime();
  if (diff < 0) {
    return "已过期";
  }
  // 小时
  const hours = Math.floor(diff / 3600000);
  // 分钟
  const minutes = Math.floor((diff % 3600000) / 60000);
  // 秒
  const seconds = Math.floor((diff % 60000) / 1000);

  return `${hours.toString().padStart(2, "0")}:${minutes
    .toString()
    .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
};
// 卸载组件时清除定时器
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value);
});
// 支付成功
const paySuccess = () => {
  payQRCodeVisible.value = false;
  router.push(
    `/orderDetails?orderSn=${orderId.value}&gid=${goodsId.value || orderStore.payInfo.goodsId}`
  );
};

// 获取企业支付账号信息
const compPayInfo = ref({});
const companyPayInfo = async () => {
  try {
    const res = await getCompanyPayInfo();
    console.log(res);
    compPayInfo.value = res.data;
  } catch (e) {
    console.log(e);
  }
};
// 复制文本
const copyText = (str)=>{
  const textarea = document.createElement('textarea');
  textarea.value = str;
  textarea.style.position = 'fixed';  // 防止页面滚动
  document.body.appendChild(textarea);
  textarea.select();

  try {
    const successful = document.execCommand('copy');
    if (!successful) {
      ElMessage.error('复制失败');
    }
    ElMessage.success({
      message: '复制成功',
      duration: 1000,
      icon: Check,
      plain: true
    });
  } catch (err) {
    ElMessage.error({
      message: '无法复制',
      duration: 1000,
    });
  }

  document.body.removeChild(textarea);
}

// 企业支付-我已完成打款
const serialNumber = ref('')
const createQYOrder = async ()=>{
  if(!serialNumber.value){
    ElMessage.warning('请填写打款流水号！')
    return
  }
  try{
    const params = {
      goodsId: orderStore.payInfo.goodsId,
      orderMobile: userInfo.value.phonenumber || '',
      goodsSpeci: orderStore.payInfo.goodsSpeci,
      accountName: compPayInfo.value.accountName,
      bankAccount: compPayInfo.value.bankAccount,
      depositBank: compPayInfo.value.depositBank,
      serialNumber: serialNumber.value
    }
    const res = await createOrderBank(params)
    ElMessage.success('提交成功，请等待财务确认！')
    setTimeout(()=>{
      paySuccess()
    },500)
  }catch(err){
    console.log(err)
  }
}
</script>

<template>
  <BaseHeaderMenuWhite bg-color="white" />
  <div class="pay-container">
    <div class="pay-title">技能猴子收银台</div>
    <p class="pay-price"><span>￥</span>{{ orderStore.payInfo.goodsAmount || amount }}</p>
    <p class="pay-time" v-if="orderStore.payInfo.goodsAmount">
      支付剩余时间：<span :class="{ 'order-close': orderExpireTimeText === '已过期' }">{{
        orderExpireTimeText
      }}</span>
    </p>
    <p v-if="amount" class="pay-time">订单加价支付</p>
    <div class="pay-way-container">
      <p class="pay-way">请选择支付方式</p>
      <div class="pay-way-list">
        <div
          class="pay-way-item"
          v-for="item in payWayList"
          :key="item.value"
          @click="selectPayWay(item.value)"
        >
          <img class="pay-way-item-icon" :src="item.icon" alt="" />
          <p class="pay-way-item-info">
            <span class="pay-way-item-name">{{ item.name }} </span>
            <span class="pay-way-item-description">{{ item.description }}</span>
          </p>
          <p>
            <span class="pay-way-item-company">{{ item.company }}</span>
          </p>
          <div class="pay-way-item-checked" :class="{ checked: item.checked }">
            <img v-if="item.checked" src="~/assets/pay-select.png" alt="" />
            <span v-else></span>
          </div>
        </div>
      </div>
    </div>
    <div v-if="payWay === 'card' && buyerInfo" class="pay-card">
      <p>
        <span>账户名称：</span><span>{{ compPayInfo.accountName }}</span>
        <span @click="copyText(compPayInfo.accountName)">复制</span>
      </p>
      <p>
        <span>银行账号：</span><span>{{ compPayInfo.bankAccount }}</span>
        <span @click="copyText(compPayInfo.bankAccount)">复制</span>
      </p>
      <p>
        <span>开户银行：</span><span>{{ compPayInfo.depositBank }}</span>
        <span @click="copyText(compPayInfo.depositBank)">复制</span>
      </p>
      <p>
        <span>付款金额：</span><span>{{ orderStore.payInfo.amount || amount }}</span>
        <span @click="copyText(orderStore.payInfo.amount || amount)">复制</span>
      </p>
    </div>
    <el-button
      class="pay-btn"
      @click="payHandle"
      :loading="qrcodeLoading"
      :disabled="qrcodeLoading"
    >
      {{ payWay === "card" ? "我已完成打款" : "立即支付" }}
    </el-button>
  </div>
  <!-- 扫码支付 -->
  <DialogPayQRCode
    v-if="payQRCodeVisible"
    @close="payQRCodeVisible = false"
    @refreshQRCode="payHandle"
    @paySuccess="paySuccess"
    :payData="payData"
  />
  <!-- 还未绑定企业 -->
  <DialogAddCompany
    v-if="addCompanyVisible"
    @close="addCompanyVisible = false"
    @joinCompany="joinCompany"
  />
  <!-- 请联系管理员添加你的手机号 -->
  <DialogCompanyAddPhone v-if="addPhoneVisible" @close="addPhoneVisible = false" />
</template>

<style scoped lang="scss">
.pay-container {
  width: 1104px;
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  margin: 112px auto 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.pay-title {
  font-size: 24px;
  font-weight: bold;
  color: #191e28;
  text-align: center;
  margin: 60px 0 24px 0;
}
.pay-price {
  font-size: 48px;
  font-weight: 500;
  color: #ff4f4f;
  font-weight: bold;
  margin-bottom: 8px;
  span {
    font-size: 20px;
  }
}
.pay-time {
  font-size: 12px;
  color: #191e28;
  width: 181px;
  height: 28px;
  line-height: 28px;
  background: rgba(25, 30, 40, 0.02);
  border-radius: 100px 100px 100px 100px;
  text-align: center;

  .order-close {
    color: #ff4f4f;
  }
}
.pay-way-container {
  width: 704px;
  margin-top: 36px;
}
.pay-way {
  font-size: 16px;
  font-weight: bold;
  color: #191e28;
  margin-bottom: 24px;
}
.pay-way-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  .pay-way-item {
    height: 80px;
    background: #ffffff;
    border-radius: 16px 16px 16px 16px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    display: flex;
    align-items: center;
    padding: 0 20px;
    cursor: pointer;
  }
  .pay-way-item-icon {
    width: 40px;
    height: 40px;
    margin-right: 16px;
  }
  .pay-way-item-info {
    flex: 1;
  }
  .pay-way-item-name {
    font-size: 16px;
    font-weight: bold;
    color: #191e28;
    margin-right: 8px;
  }
  .pay-way-item-description {
    font-size: 14px;
    color: rgba(25, 30, 40, 0.48);
  }
  .pay-way-item-company {
    font-size: 14px;
    color: #019a81;
  }
  .pay-way-item-checked {
    width: 24px;
    height: 24px;
    margin-left: 34px;
    cursor: pointer;
    span {
      display: inline-block;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background: #ffffff;
      border: 1px solid rgba(25, 30, 40, 0.08);
      box-sizing: border-box;
    }
    img {
      width: 24px;
      height: 24px;
    }
  }
}
.pay-btn {
  width: 220px;
  height: 48px;
  background: #1dbf73;
  border-radius: 8px 8px 8px 8px;
  font-size: 16px;
  font-weight: bold;
  color: #ffffff;
  text-align: center;
  line-height: 48px;
  margin-bottom: 60px;
  margin-top: 60px;
  cursor: pointer;
}
.pay-card {
  width: 704px;
  background: rgba(25, 30, 40, 0.02);
  border-radius: 12px 12px 12px 12px;
  padding: 20px;
  box-sizing: border-box;
  margin-top: 12px;
  P {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    font-size: 14px;
    &:last-child {
      margin-bottom: 0;
    }
    span:nth-child(1) {
      color: rgba(25, 30, 40, 0.6);
    }
    span:nth-child(2) {
      flex: 1;
      color: #191e28;
    }
    span:nth-child(3) {
      color: #019a81;
      cursor: pointer;
    }
  }
}
</style>
